<?php
declare (strict_types = 1);

namespace app\backend_api\controller;

use app\backend_api\model\AdminUsers;
use app\backend_api\validate\AdminValidate;
use app\BaseController;
use think\db\exception\DbException;
use think\Request;

class Admin extends BaseController
{
    /**
     * 显示角色列表
     * @return \think\Response
     * @throws DbException
     */
    public function list(): \think\Response
    {
        $page = input('currentPage', 1);
        $pageSize = input('pageSize', 4);

//        $admin = AdminUsers::find(3);
//        dd($admin->roles->toArray());
        $query = AdminUsers::with(['allRoles' => function($query) {
            $query->getQuery()->where('status',1)->field('role_name')->hidden(['pivot']);
        }])->order('id', 'DESC')->paginate(['page' => $page, 'list_rows' => $pageSize]);

        // 将关联的别名改为 roles
        $query->each(function ($item) {
            $item->roles = $item->allRoles;
            unset($item->allRoles);
        });

//        dd($query->toArray());
//        $query = AdminUsers::alias('au')
//            ->join('admin_with_roles awr', 'au.id = awr.admin_id')
//            ->join('admin_roles ar', 'awr.role_id = ar.id')
//            ->where('ar.status', 1)
//            ->field('au.*,ar.role_name')
//            ->order('au.id', 'DESC')
//            ->paginate(['page' => $page, 'list_rows' => $pageSize]);

        $data = [
            'current_page' => $query->currentPage(),
            'per_page' => $pageSize,
            'count_page' => $query->lastPage(),
            'total' => $query->total(),
            'data' => $query->items(),
        ];
        return $this->success($data);

    }

    /**
     * 显示指定的角色
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id): \think\Response
    {
        return $this->success(AdminUsers::find($id));
    }

    /**
     * 保存更新的资源
     * @return \think\Response
     */
    public function update(AdminValidate $adminValidate)
    {
        $editId = input('userId', 0);
        if ($editId) {
            $params = $adminValidate->post()->goCheck('edit');
            // 查找要编辑的用户
            $admin = AdminUsers::find($editId);
            if (!$admin) {
                return $this->error('用户ID不存在');
            }
        } else {
            $params = $adminValidate->post()->goCheck();
            $admin = new AdminUsers();
        }

        $admin->name = $params['username'];
        $admin->email = $params['email'];

//        dd(password_algos());

        if (!empty($params['password'])) {
            $admin->password = password_hash($params['password'], PASSWORD_DEFAULT);
        }

        $admin->mobile = $params['mobile'];
        $admin->avatar = $params['avatar'];
        $admin->status = $params['status'];
        $admin->save();

        // 如果角色 ID 不为空，更新角色关联
        if (!empty($params['role_id'])) {
            $admin->roles()->sync($params['role_id']);
        } else {
            $admin->roles()->detach();
        }
        return $this->successMsg($editId ? '更新成功' : '提交成功');


    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $admin = AdminUsers::find($id);
        if (!$admin) {
            return $this->error('用户ID未找到');
        }
        $admin->delete();
        $admin->roles()->detach();
        return $this->successMsg('删除成功');
    }
}
